﻿# --------------------------- #
# Remote Management Functions #
# --------------------------- #

# Sends file to remote session
function Send-RemoteFile
{
	param(
        [Parameter(Mandatory = $true)]
        [string]$source,
        [Parameter(Mandatory = $true)]
        [string]$destination,
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.Runspaces.PSSession]$session)
	$script = {
		param($destination, $bytes)
		$destination = $executionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($destination)
		$file = [IO.File]::Open($destination, "OpenOrCreate")
		$position = $file.Seek(0, "End")
		$file.Write($bytes, 0, $bytes.Length)
		$file.Close()
	}
	$sourceFile = Get-Item $source
	Remove-RemoteFile -Destination $destination -Session $session
	$streamSize = 1MB
	$position = 0
	$rawBytes = New-Object byte[] $streamSize
	$file = [IO.File]::OpenRead($sourceFile.FullName)
	while (($read = $file.Read($rawBytes, 0, $streamSize)) -gt 0)
	{
		if ($read -ne $rawBytes.Length)
		{
			[Array]::Resize([ref]$rawBytes, $read)
		}
		Invoke-Command -Session $session $script -ArgumentList $destination, $rawBytes
		if ($rawBytes.Length -ne $streamSize)
		{
			[Array]::Resize([ref]$rawBytes, $streamSize)
		}
		[GC]::Collect()
		$position += $read
	}
	$file.Close()
}

# Delete remote file
function Remove-RemoteFile
{
	param(
        [Parameter(Mandatory = $true)]
        [string]$destination,
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.Runspaces.PSSession]$session
    )
	Invoke-Command -Session $session {
		if (Test-Path $args[0])
		{
			Remove-Item $args[0]
		}
	} -ArgumentList $destination
}